using DG.Tweening;
using LitJson;
using UnityEngine;

namespace CGF
{
    public partial class LoginUI : UIComponentBase, IAwake<UILayer, bool>, IDestroy
    {
        public static void Open()
        {
            UIManagerComponent.instance.OpenUI<LoginUI>(UILayer.Normal, RootComponent.instance, false);
        }

        public static void Close()
        {
            UIManagerComponent.instance.CloseUI<LoginUI>();
        }

        public async void Awake(UILayer layer, bool isFloat)
        {
            await SpawnPrefab("Prefabs/GameUI/LoginUI", layer, isFloat);
            BindProperties(transform);
            MainLaunch.Destroy();

            if (CGFConfig.Instance.ReleaseArea == EArea.Brazil)
            {
                //显示3个页签
                TextPhone.gameObject.SetActive(true);
                SwitchBg.rectTransform.sizeDelta = new Vector2(220, SwitchBg.rectTransform.sizeDelta.y);
                TextPhone.rectTransform.anchoredPosition = new Vector2(-200, 0);
                TextEmail.rectTransform.anchoredPosition = new Vector2(0, 0);
                TextUsername.rectTransform.anchoredPosition = new Vector2(200, 0);
                SwitchToPhone();
            }
            else
            {
                //显示2个页签
                TextPhone.gameObject.SetActive(false);
                SwitchBg.rectTransform.sizeDelta = new Vector2(320, SwitchBg.rectTransform.sizeDelta.y);
                TextEmail.rectTransform.anchoredPosition = new Vector2(-150, 0);
                TextUsername.rectTransform.anchoredPosition = new Vector2(150, 0);
                SwitchToUsername();
            }
            
            TextPhone.SetClick(SwitchToPhone);
            TextEmail.SetClick(SwitchToEmail);
            TextUsername.SetClick(SwitchToUsername);
            
            Version.text = $"v {CGFConfig.Instance.VersionFullName}";

            BtnLanguage.SetClick(() =>
            {
                PanelEditLanguage.Open();
            });

            BtnLogin.SetClick(() =>
            {
                if (InputPhone.gameObject.activeSelf)
                {
                    InputPhone.GetComponent<LoginUIPhone>().Login();
                }
                else if (InputUsername.gameObject.activeSelf)
                {
                    InputUsername.GetComponent<LoginUIUsername>().Login();
                }
                else
                {
                    InputEmail.GetComponent<LoginUIEmail>().Login();
                }
            });

            TextGoReggister.SetClick(() =>
            {
                PanelRegister.Open();
            });

            BtnGoogle.SetClick(() =>
            {
                Wait.Open();
                FirebaseHelper.GoogleSignIn(ReqLoginByFirebaseToken);
            });

            BtnFacebook.SetClick(() =>
            {
                Wait.Open();
                FirebaseHelper.FacebookSignIn(ReqLoginByFirebaseToken);
            });

            OnLanguageChange();
            PanelEditLanguage.onLanguageChange += OnLanguageChange;

            CheckOtherWays();
        }

        private async void CheckOtherWays()
        {
            /* 谷歌号已被封
            TextOR.gameObject.SetActive(false);
            BtnGoogle.gameObject.SetActive(false);
            BtnFacebook.gameObject.SetActive(false);

            await CTask.Wait(0.1f);
            if (Application.isEditor) return;

            FirebaseHelper.SignOut();
            FirebaseHelper.Init(success =>
            {
                if (success)
                {
                    TextOR.gameObject.SetActive(true);
                    BtnGoogle.gameObject.SetActive(true);
                    BtnFacebook.gameObject.SetActive(true);
                }
            });*/
        }

        private void SwitchToPhone()
        {
            TextPhone.text.color = Color.white;
            TextEmail.text.color = TextUsername.text.color = new Color(1, 1, 1, 0.25f);
            InputPhone.gameObject.SetActive(true);
            InputCode.gameObject.SetActive(true);
            InputUsername.gameObject.SetActive(false);
            InputPassword.gameObject.SetActive(false);
            TextGoReggister.gameObject.SetActive(false);
            InputEmail.gameObject.SetActive(false);
            InputInviteCode.gameObject.SetActive(true);
            SwitchBg.rectTransform.DOAnchorPosX(TextPhone.rectTransform.anchoredPosition.x, 0.2f).SetEase(Ease.OutBack);
        }

        private void SwitchToEmail()
        {
            TextEmail.text.color = Color.white;
            TextPhone.text.color = TextUsername.text.color = new Color(1, 1, 1, 0.25f);
            InputPhone.gameObject.SetActive(false);
            InputUsername.gameObject.SetActive(false);
            InputPassword.gameObject.SetActive(false);
            InputEmail.gameObject.SetActive(true);
            InputCode.gameObject.SetActive(true);
            TextGoReggister.gameObject.SetActive(false);
            InputInviteCode.gameObject.SetActive(true);
            SwitchBg.rectTransform.DOAnchorPosX(TextEmail.rectTransform.anchoredPosition.x, 0.2f).SetEase(Ease.OutBack);
        }

        private void SwitchToUsername()
        {
            TextUsername.text.color = Color.white;
            TextPhone.text.color = TextEmail.text.color = new Color(1, 1, 1, 0.25f);
            InputPhone.gameObject.SetActive(false);
            InputCode.gameObject.SetActive(false);
            InputUsername.gameObject.SetActive(true);
            InputPassword.gameObject.SetActive(true);
            TextGoReggister.gameObject.SetActive(true);
            InputEmail.gameObject.SetActive(false);
            InputInviteCode.gameObject.SetActive(false);
            SwitchBg.rectTransform.DOAnchorPosX(TextUsername.rectTransform.anchoredPosition.x, 0.2f).SetEase(Ease.OutBack);
        }

        //发给自己的服务端验证
        private async void ReqLoginByFirebaseToken(string token)
        {
            if (string.IsNullOrEmpty(token))
            {
                Wait.Close();
                Dialog.Alert(I18N_login_fail);
                return;
            }
            JsonData data = new JsonData();
            data["token"] = token;
            var res = await HttpHelper.PostJson(Config.Get.APIBaseUrl + "/v1/ai/oauth/sso/google/bind", data);
            if (!res.success)
            {
                Wait.Close();
                Dialog.Alert(I18N_login_fail);
                return;
            }
            OnLogin(res.text);
        }

        public void OnLogin(JsonData json)
        {
            if (json == null)
            {
                Wait.Close();
                Dialog.Alert(gameObject.GetComponent<I18N>().GetTextByKey("login_fail"));
                return;
            }

            if ((int)json["code"] != 200)
            {
                Wait.Close();
                Dialog.Alert(json["message"].ToString());
                return;
            }

            Wait.Close();
            UserInfo.OnLogin(json["data"]);
            Close();
            GameUI.Open();
        }

        private void OnLanguageChange()
        {
            BtnSendCode.text.text = CommAssets.instance.I18N_send_code;
            Flag.sprite = Flag.gameObject.Get<Sprite>((int)I18N.CurrLanguage);
        }

        public override void OnDestroy()
        {
            base.OnDestroy();
            PanelEditLanguage.onLanguageChange -= OnLanguageChange;
        }
    }
}
